import router from './router';
import { getToken, getRoles } from './utils/auth'; // get token from cookie

const whiteList = ['/login']; // no redirect whitelist

router.beforeEach(async (to, from, next) => {
	// console.log('beforeEach: from', from);

	// determine whether the user has logged in
	const hasToken = getToken();
	// console.log(hasToken)
	if (hasToken) {
		// console.log(1)
		if (to.path === '/login') {
			// console.log(2)
			// if is logged in, redirect to the home page
			next({ path: '/' });
		} else {
			// console.log(3)
			const roles = getRoles();
			// console.log(roles)
			const routes = router.getRoutes().filter(r => r.path === to.path) as any;
			if (routes.length) {
				// Permission filtering
				const toRoute = routes[0];
				if ( (toRoute.meta && !toRoute.meta.roles) || (toRoute.meta && toRoute.meta.roles.includes(roles)) ) {
					next();
				} else {
					next('/401');
				}
			} else {
				// Otherwise jump to 404
				next('/404');
			}
		}
	} else {
		// console.log(4)
		/* has no token*/
		if (whiteList.includes(to.path)) {
			// in the free login whitelist, go directly
			next();
		} else {
			// other pages that do not have permission to access are redirected to the login page.
			// next('/login');
			next();
		}
	}
});

router.afterEach(() => {
	// finish progress bar
});